import { PlusOutlined } from '@ant-design/icons';
import {Button, Divider, message, Popconfirm, Select, TreeSelect} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryRule, updateRule, addRule, removeRule } from './service';
import styles from '../../../global.less';
import { transTitle } from '@/utils/utils';
import FormItem from 'antd/lib/form/FormItem';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updataState, handleUpdataState] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [parentName, setParentName] = useState();
  const TreeOnChange = (value, label, extra) => {
    handleTreeValue(label.id);
    setParentName(label.name);
  };
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '规则名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '描述信息',
      hideInSearch: true,
      dataIndex: 'remark',
    },
    {
      title: '是否统采',
      dataIndex: 'purchaseType',
      hideInSearch: true,
      valueEnum: {
        false: {
          text: '否',
          status: 'Error',
        },
        true: {
          text: '是',
          status: 'Processing',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select defaultValue={defaultRender.appType} placeholder="请选择此分类是否归属统采" allowClear>
            <Select.Option value={false}>否</Select.Option>
            <Select.Option value={true}>是</Select.Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '是否统采必填项',
          },
        ],
      },
    },
    {
      title: '父级',
      hideInSearch: true,
      hideInTable: true,
      dataIndex: 'parentId',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onSelect={TreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <Access accessKey={"@updateClassification"}>
              <a
                onClick={() => {
                  handleUpdataState(true);
                  handleModalVisible(true);
                  setStepFormValues(record);
                }}
              >
                修改
              </a>
              <Divider type="vertical" />
            </Access>
            <Access accessKey={"@deleteClassification"}>
              <Popconfirm
                placement="top"
                title="确定要删除吗?"
                onConfirm={() => {
                  handleRemove(record.id, actionRef);
                }}
                okText="确定"
                cancelText="取消"
              >
                <a>删除</a>
              </Popconfirm>
            </Access>

          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="分类列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 1200 }}
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Access accessKey={"@newClassification"}>
            <Button
              type="primary"
              onClick={() => {
                handleModalVisible(true);
                handleUpdataState(false);
                queryRule({})
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          </Access>
          ,
        ]}
        request={(params, sorter, filter) => queryRule({...params})}
        postData={(payload) => {
          // const { data, total } = payload;
          transTitle(payload);
          setMenuValues(payload);

          // setCount(total);
          return payload||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm
        width={800}
        title={updataState ? '修改分类' : '新增分类'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            updataState ? (value.id = stepFormValues.id) : null;
            const success = updataState ? await handleUpdate(value) : await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: updataState === true ? stepFormValues : null,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
